package pers.qianyu.module.logging.aspect;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import pers.qianyu.module.core.domain.logging.dto.RequestLogDTO;
import pers.qianyu.module.logging.annotation.ControllerLog;
import pers.qianyu.module.logging.service.RequestLogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 操作日志记录处理
 *
 * @author mizzle rain
 * @date 2020年11月10日16:47:51
 */
@Aspect
@Component
public class ControllerLogAspect {
    @Autowired
    private RequestLogService requestLogService;
    @Value("${enable-controller-log}")
    private boolean enableControllerLog;

    @Pointcut("@annotation(pers.qianyu.module.logging.annotation.ControllerLog)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        if (!enableControllerLog) {
            return;
        }
        try {
            // 获得注解
            ControllerLog controllerLog = getAnnotationLog(joinPoint);
            if (Objects.isNull(controllerLog)) {
                return;
            }

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.isNull(attributes)) {
                return;
            }
            HttpServletRequest req = attributes.getRequest();
            RequestLogDTO requestLogDTO = new RequestLogDTO();
            requestLogDTO.setIp(Objects.nonNull(req.getHeader("X-Real-IP"))
                    ? req.getHeader("X-Real-IP") : req.getRemoteAddr());
            requestLogDTO.setUrl(req.getRequestURL().toString());
            requestLogDTO.setRequestMethod(req.getMethod());
            requestLogDTO.setClassMethod(joinPoint.getSignature().toString());
            requestLogDTO.setUserAgent(req.getHeader("user-agent"));
            if (Objects.nonNull(e)) {
                requestLogDTO.setException(e.toString());
            }
            // 处理设置注解上的参数
            requestLogDTO.setBusinessType(controllerLog.businessType());
            if (controllerLog.isSaveRequestData()) {
                requestLogDTO.setRequestParameters(argsArrayToString(joinPoint.getArgs()));
            }
            if (controllerLog.isSaveResultData()) {
                requestLogDTO.setResult(JSONUtil.toJsonStr(jsonResult));
            }
            // 保存数据库
            requestLogService.insertAsync(requestLogDTO);
        } catch (Exception exp) {
            LogFactory.get().error("[日志写入异常] 异常信息:{}", exp.toString());
            exp.printStackTrace();
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private ControllerLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        return Objects.nonNull(method) ? method.getAnnotation(ControllerLog.class) : null;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        return Optional.ofNullable(paramsArray)
                .map(Arrays::stream)
                .orElseGet(Stream::empty)
                .filter(o -> !this.isFilterObject(o))
                .map(JSON::toJSONString)
                .collect(Collectors.joining(" "));
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o) {
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }
}
